//
//  BookParserDelegate.m
//  ReadJapanese
//
//  Created by 병철 김 on 11. 7. 29..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BookParserDelegate.h"
#import "CoreDataManager.h"


@implementation BookParserDelegate
@synthesize context, bookCount, book, entityName;

#pragma mark - initialize
- (id)init {
	self = [super init];
	if (self) {
		elementString = [[NSArray alloc] initWithObjects:@"book", @"info", @"bookId", @"title", @"mainLanguage", @"subLanguage", @"lines", @"level", @"image", @"s", @"a", @"b"
						 , @"author", @"offset", @"studyTypes", @"desc", @"media", @"scriptSize", @"mediaSize", @"authorImage", @"length", nil];
		pid = [NSNumber numberWithInt:0];
	}
	return self;
}

#pragma mark - xml sax parsing
- (void) parserDidStartDocument:(NSXMLParser *)parser {

}

- (void) parserDidEndDocument:(NSXMLParser *)parser {
	NSError *error;
	[context save:&error];
}

- (NSNumber*) getNumberAttribute:(NSString*) attributeName attributes:(NSDictionary*) attributeDict {
	NSString *value = [attributeDict objectForKey:attributeName];
	NSNumberFormatter *formatter = [self numberFormatter];
	return [formatter numberFromString:value];
}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
	BOOK_ELEMENTS curElement = [elementString indexOfObject:elementName];
	
	switch (curElement) {
		case E_book :
			if (book == nil && entityName != nil) {
				book = [[CoreDataManager sharedCoreDataManager] insertOneInto:entityName values:nil];
			}
			break;
		case E_s : {
			NSNumber *sid = [self getNumberAttribute:@"id" attributes:attributeDict];
			NSNumber *start = [self getNumberAttribute:@"s" attributes:attributeDict];
			NSNumber *duration = [self getNumberAttribute:@"d" attributes:attributeDict];
			NSNumber *paragraph = [self getNumberAttribute:@"p" attributes:attributeDict];
			if ([paragraph boolValue]) {
				pid = [NSNumber numberWithInt:([pid intValue]+1)];
			}
            
            start = [NSNumber numberWithFloat:([start floatValue] / 1000.0)];
            duration = [NSNumber numberWithFloat:([duration floatValue] / 1000.0)];
			//TODO 여기서 paragraph 처리
			sentence = [[CoreDataManager sharedCoreDataManager] insertOneInto:@"Sentence" values:@"book", book, @"sid", sid, @"start", start, @"duration", duration, @"paragraph", paragraph, @"pid", pid, nil];
			break;
		}
		case E_bookId :
		case E_title :
		case E_mainLanguage :
		case E_subLanguage :
		case E_lines :
		case E_level :
		case E_image :
		case E_a :
		case E_b :
		case E_author :
		case E_offset :
		case E_studyTypes :
		case E_desc :
		case E_media :
		case E_scriptSize :
		case E_mediaSize :
        case E_authorImage :
        case E_length :
			fReadCharacters = true;
			break;
		default:
			break;
	}
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	BOOK_ELEMENTS curElement = [elementString indexOfObject:elementName];
	
	switch (curElement) {
		case E_book :
			bookCount++;
			book = nil;
			break;
		case E_bookId :
		case E_lines :
		case E_level : 
		case E_offset :
		case E_scriptSize : 
        case E_length :
		case E_mediaSize : {
			NSNumberFormatter *formatter = [self numberFormatter];
			NSNumber *number = [formatter numberFromString:stringValue];
			[book setValue:number forKey:elementName];
			break;
		}
		case E_title :
		case E_mainLanguage :
		case E_subLanguage :
		case E_image :
		case E_author :
		case E_studyTypes :
		case E_desc :
		case E_media :
        case E_authorImage :
            [stringValue replaceOccurrencesOfString:@"\t" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [stringValue length])];
			[stringValue replaceOccurrencesOfString:@"\n" withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [stringValue length])];
			[stringValue replaceOccurrencesOfString:@"\r" withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [stringValue length])];
			[book setValue:stringValue forKey:elementName];
			break;
		case E_a:
		case E_b:
			[stringValue replaceOccurrencesOfString:@"\t" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [stringValue length])];
			[stringValue replaceOccurrencesOfString:@"\n" withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [stringValue length])];
			[stringValue replaceOccurrencesOfString:@"\r" withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, [stringValue length])];
			[sentence setValue:stringValue forKey:elementName];
			break;
		default:
			break;
	}
	
	if (stringValue != nil) {
		[stringValue release];
		stringValue = nil;
	};
	fReadCharacters = false;
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	if (!fReadCharacters) return;
	
	if (!stringValue) {
		stringValue = [[NSMutableString alloc] initWithCapacity:50];
	}
	[stringValue appendString:string];
}

- (void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString {
	// SKIP
	return;
}

#pragma mark - accessor
- (NSNumberFormatter*) numberFormatter {
	if (numberFormatter == nil) {
		numberFormatter = [[NSNumberFormatter alloc] init];
		[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
	}
	return numberFormatter;
}

#pragma mark - clean up
- (void) dealloc {
	[book release];
	[context release];
	[numberFormatter release];
	[entityName release];
	[super dealloc];
}

@end
